<template>
  <div
    class="canvas-title"
    :style="{
      height: menuButtonInfo.height + 8 + 'px',
      lineHeight: menuButtonInfo.height + 5 + 'px',
    }"
    >出库签名</div
  >
  <canvas
    class="autograph-canvas"
    type="2d"
    disable-scroll
    id="myCanvas"
    canvas-id="myCanvas"
    :style="{ width: props.width, height: props.height, display: 'block' }"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @touchcancel="handleTouchEnd"
    @error="handleTouchEnd"
  >
    <div class="canvas-tips">
      <uv-button text="擦除重签" @click="clearCanvas"></uv-button>
    </div>
  </canvas>
  <div style="margin-top: 10rpx">
    <uv-row justify="space-around">
      <uv-col span="2">
        <uv-button text="返回" @click="back"></uv-button>
      </uv-col>
      <uv-col span="2">
        <uv-button
          type="primary"
          text="确认签名"
          :loading="loading"
          @click="getOnlieUrl"
        ></uv-button>
      </uv-col>
    </uv-row>
  </div>
</template>

<script setup lang="ts">
  import { getCurrentInstance } from 'vue';
  import { uploadFile } from '@/utils/upload';

  const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
  const uploadImg = ref();
  const back = () => {
    uni.navigateBack();
  };
  // 计算状态栏高度
  console.log(menuButtonInfo, '菜单按钮信息');
  let myCanvas: any = null;
  const loading = ref(false);
  const instance = getCurrentInstance();
  const props = defineProps({
    width: {
      type: String,
      default: '90%',
    },
    height: {
      type: String,
      default: '260rpx',
    },
    lineWidth: {
      type: Number,
      default: 2,
    },
    lineColor: {
      type: String,
      default: '#000000',
    },
  });
  const state = reactive({
    isDraw: false, // 是否能画画
    canvasElement: null,
    canvasContext: null,
    oldPosition: {
      x: 0,
      y: 0,
    },
  });
  // 初始化canvas
  const initCanvas = (fn) => {
    const query = uni.createSelectorQuery().in(instance);
    query
      .select('#myCanvas')
      .fields({
        node: true,
        size: true,
        context: true,
      })
      .exec((res) => {
        const canvas = res[0].node;
        const context = canvas.getContext('2d');
        const dpr = uni.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        context.scale(dpr, dpr);
        myCanvas = canvas;
        state.canvasContext = context;
        console.log(res, dpr, canvas, myCanvas.width);
        fn && fn();
      });
  };
  onMounted(() => {
    initCanvas();
  });
  // 描绘canvas
  const drawCanvas = (position) => {
    if (state.canvasContext) {
      state.canvasContext.strokeStyle = props.lineColor;
      state.canvasContext.lineWidth = props.lineWidth;
      state.canvasContext.beginPath();
      state.canvasContext.moveTo(state.oldPosition.x, state.oldPosition.y);
      state.canvasContext.lineTo(position.x, position.y);
      state.canvasContext.stroke();
      state.canvasContext.closePath();
      state.oldPosition = {
        x: position.x,
        y: position.y,
      };
    }
  };
  // 在画布触摸开始
  const handleTouchStart = (e) => {
    const x = e.touches[0].x;
    const y = e.touches[0].y;
    state.oldPosition = {
      x: x,
      y: y,
    };
    state.isDraw = true;
  };
  // 在画布触摸移动
  const handleTouchMove = (e) => {
    if (state.isDraw) {
      let positionItem = e.touches[0];
      if (state.canvasContext) {
        drawCanvas(positionItem, true);
      } else {
        initCanvas(() => {
          drawCanvas(positionItem, true);
        });
      }
    }
  };
  // 在画布触摸结束
  const handleTouchEnd = () => {
    state.isDraw = false;
  };
  // 清除画布
  const clearCanvas = () => {
    loading.value = false;
    if (myCanvas) {
      const x = myCanvas.width;
      const y = myCanvas.height;
      state.canvasContext.clearRect(0, 0, x, y);
    }
  };

  // 获取临时文件
  const getCavasTempFile = () => {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath(
        {
          canvas: myCanvas,
          destWidth: '600',
          destHeight: '260',
          fileType: 'png',
          success: (res) => {
            resolve(res);
            console.log('临时文件生成成功', res);
          },
          fail: (e) => {
            console.log('e', e);
            reject('图片临时文件生成失败');
          },
        },
        instance,
      );
    });
  };
  const getOnlieUrl = async () => {
    loading.value = true;
    const url = await getCavasTempFile();
    const base64 = uni.getFileSystemManager().readFileSync(url.tempFilePath, 'base64');
    try {
      uni.showLoading({
        title: '上传中',
      });
      const result = await uploadFile(uni.base64ToArrayBuffer(String(base64)), 'png', 'erp');
      console.log(result, '上传成功');
      uploadImg.value = result;
      loading.value = false;
      uni.hideLoading();
      uni.navigateBack();
    } catch (error: any) {
      uni.showToast({
        title: error.data.message,
        icon: 'none',
        duration: 3000,
      });
      loading.value = false;
      uni.hideLoading();
      uni.showToast({
        title: '上传失败',
        icon: 'none',
        duration: 3000,
      });
    }
  };
  onBeforeUnmount(() => {
    onToparend(uploadImg.value);
  });

  function onToparend(type) {
    const instance = getCurrentInstance().proxy;
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.emit('acceptDataFromOpenedPage', {
      data: type,
    });
  }
</script>

<style lang="scss" scoped>
  .canvas-title {
    text-align: center;
  }
  .autograph-canvas {
    border: 1px solid #ccc;
    margin: 0 auto;
    box-sizing: border-box;
  }
  .canvas-tips {
    float: right;
    margin: 5rpx 5rpx 0 0;
    box-sizing: border-box;
  }
</style>
